#include"heap2.h"

void HeapInit(HP* php)
{
	assert(php);
	php->a = (int*)malloc(sizeof(int) * 4);
	if (php->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	php->size = 0;
	php->capacity = 4;
}

void Swap(int* n1, int* n2)
{
	int x = *n1;
	*n1 = *n2;
	*n2 = x;
}

void AdjustUp(int* a, int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}
void AdjustDown(int* a, int n, int parent)
{
	int child = parent * 2 + 1;
	if (child + 1 > n && a[child + 1] > a[child])
	{
		child++;
	}
	if (a[child] > a[parent])
	{
		Swap(&a[child], &a[parent]);
		parent = child;
		child = parent * 2 + 1;
	}
	else
	{
		return;
	}
}

void HeapDestroy(HP* php)
{
	assert(php);
	if (php->size == 0)
	{
		return;
	}
	else
	{
		php->size = 0;
		php->capacity = 0;
	}

}
void HeapPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int* tmp = (int*)realloc(php->a, sizeof(int) * php->capacity * 2);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		php->a = tmp;
		php->capacity *= 2;
	}
	php->a[php->size] = x;
	php->size++;
	AdjustUp(php->a, php->size - 1);
}
void HeapPop(HP* php)
{
	assert(php);
	if (php->size == 0)
	{
		return;
	}
	else
	{
		Swap(&php->a[0], &php->a[php->size - 1]);
		php->size--;
		AdjustDown(php->a, php->size, 0);
	}
}
HPDataType HeapTop(HP* php)
{
	assert(php);
	return php->a[0];
}
bool HeapEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}
int HeapSize(HP* php)
{
	assert(php);
	return php->size;
}
